<template>
  <!-- 标题 -->
  <p class="title">{{ pageData.title }}</p>

  <!-- 表格 -->
  <Table ref="tableRef" :search="search" :tools="tools" :columns="columns" :api="getFeedback" />

  <!-- 增加模态框 -->
  <n-modal v-model:show="pageData.isShowAddModel" :mask-closable="false" preset="dialog" title="增加" positive-text="确定"
    negative-text="取消" style="width: 600px" @positive-click="add" @negative-click="addCancel"
    @after-leave="closeAddModel">
    <Form :config="addFormConfig" ref="addFormRef" />
  </n-modal>

  <!-- 修改模态框 -->
  <n-modal v-model:show="pageData.isShowUpdateModel" :mask-closable="false" preset="dialog" title="编辑"
    positive-text="确定" negative-text="取消" style="width: 600px" @positive-click="update" @negative-click="updateCancel"
    @after-leave="closeUpdateModel">
    <Form ref="updateFormRef" :config="updateFormConfig" />
  </n-modal>

</template>

<script setup lang="ts">
import { getFeedback, addFeedback, updateFeedback, deleteFeedback } from '@/api/system/user';
import { NButton, NSpace } from 'naive-ui';
import { h, reactive, ref } from 'vue';
import { addFormConfig, updateFormConfig } from './config'
import { useRoute } from 'vue-router'
import { deepClone } from '@/utils/lib/clone';
import { formatDate } from '@/utils/lib/date';
import { useUserStore } from '@/store/modules/user'
import { storeToRefs } from "pinia";


const userStore = useUserStore()
const { info } = storeToRefs(userStore)

const addFormRef = ref()
const updateFormRef = ref()
const tableRef = ref()


const route = useRoute()

const closeUpdateModel = () => {
  pageData.isShowUpdateModel = false
}

const closeAddModel = () => {
  pageData.isShowAddModel = false
}

/**
 * 增加启事
 */
const add = async () => {
  try {
    const instance = addFormRef.value.getFormRef()
    console.log(instance.model);
    instance.validate(async (err) => {
      if (!err) {
        let data = {
          ...instance.model,
          user_id: info.value.user_id,
        }
        data.TIME = formatDate(new Date(data.date)).slice(0, 10) + ' ' + formatDate(new Date(data.time)).slice(-8)
        delete data.date
        delete data.time
        await addFeedback(data)
        tableRef.value.getData()
      } else {
        window['$message'].error('增加反馈失败')
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 更新反馈
 */
const update = async () => {
  try {
    const instance = updateFormRef.value.getFormRef()
    // console.log(instance.model);
    instance.validate(async (err) => {
      if (!err) {
        let data = {
          ...instance.model,
          id: pageData.selectedRow.id,
        }
        data.TIME = formatDate(new Date(data.date)).slice(0, 10) + ' ' + formatDate(new Date(data.time)).slice(-8)
        delete data.date
        delete data.time
        console.log(data);

        await updateFeedback(data)
        tableRef.value.getData()
      } else {
        window['$message'].error('修改反馈失败')
      }
    })


  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 增加弹窗取消
 */
const addCancel = () => {
  pageData.isShowAddModel = false
}


/**
 * 更新弹窗取消
 */
const updateCancel = () => {
  pageData.isShowUpdateModel = false
}

const addInfo = (val) => {
  console.log('add', val);
  pageData.isShowAddModel = true
}

const editFeedback = (row) => {
  console.log('edit', row);
  pageData.selectedRow = deepClone(row)
  pageData.isShowUpdateModel = true
  updateFormConfig.formItems.forEach(item => {
    if (item.field === 'topic') {
      item.value = row.topic
    }
    if (item.field === 'advise') {
      item.value = row.advise
    }
    if (item.field === 'date') {
      item.value = new Date(row.TIME.slice(0, 10)).getTime()
    }
    if (item.field === 'time') {
      item.value = new Date(row.TIME.slice(-8)).getTime()
    }
  })
}

/**
 * 删除反馈
 */
const deleteInfo = async (row) => {
  try {
    console.log('delete', row);
    window['$dialog'].success({
      title: '删除',
      content: '是否删除该条数据？',
      maskClosable: false,
      negativeText: '取消',
      positiveText: '确定',
      onPositiveClick: async () => {
        await deleteFeedback({
          id: row.id
        })
        tableRef.value.getData()
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 搜索栏
 */
const search = []

/**
 * 工具栏按钮
 */
const tools = [
  {
    name: '新增反馈',
    type: 'error',
    handleClick: addInfo
  }
]

/**
 * 表格
 */
const columns = [
  {
    title: '发布者',
    key: 'user_id',
    width: 100,
  },
  {
    title: '主题',
    key: 'topic',
    width: 100,
  },
  {
    title: '内容',
    key: 'advise',
    width: 250,
    ellipsis: true
  },
  {
    title: '发布时间',
    key: 'TIME',
    ellipsis: true,
    width: 200,
  },
  {
    title: '操作',
    key: 'action',
    render(row) {
      return h(NSpace, null, [
        h(NButton, {
          type: 'info',
          size: 'small',
          onClick: () => editFeedback(row)
        }, () => '编辑'),
        h(NButton, {
          type: 'error',
          size: 'small',
          onClick: () => deleteInfo(row)
        }, () => '删除')
      ])
    }
  }
]


const pageData = reactive({
  selectedRow: {} as any,
  isShowAddModel: false as boolean,
  isShowUpdateModel: false as boolean,
  title: route.meta.title as string,
})


</script>

<style scoped lang="less">
@import '@/styles/mixin.less';

.title {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

.img-box {
  .flex(row, flex-start, center);
  padding-left: 30px;

  .name {
    span {
      color: #d03050;
    }
  }

  .img {
    // margin-top: 10px;
    margin-left: 10px;
    width: 100px;
    height: 100px;
    border: 2px dotted #ccc;
    background-color: rgb(250, 250, 252);
    .flex(row, center, center);
    cursor: pointer;

    p {
      font-size: 20px;
    }

    &:hover {
      border: 2px dotted green;
    }

    .icon-box {
      .flex(column, center, center);

      .icon-title {
        font-size: 14px;
        color: #666;
      }
    }
  }

  .file-input {
    display: none;
  }
}
</style>